# _*_ coding:utf-8 _*_
import webbrowser
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from time import sleep


# 查找页面所有iframe,返回iframe列表
# 单个iframe结构：{id:name:index}
# id:iframe的id
# id:iframe的name
# id:iframe在当前上下文的索引
def query_all_iframe(browser):
    iframe_paths = []
    recursion_iframes(browser, iframe_paths)
    return iframe_paths


# 通过浏览器对象和iframe递归查找iframe
def recursion_iframes(browser, iframe_paths=[], parent_iframe_path=''):
    if parent_iframe_path != '':
        switch_target_iframe(browser, parent_iframe_path)
    iframe_arr = browser.find_elements_by_css_selector("iframe")
    if len(iframe_arr) == 0:
        return
    for i in range(len(iframe_arr)):
        switch_target_iframe(browser, parent_iframe_path)
        id = iframe_arr[i].get_attribute('id')
        name = iframe_arr[i].get_attribute('name')
        iframe_path = parent_iframe_path + "/{"+id+":"+name+":"+str(i)+"}"
        iframe_paths.append(iframe_path)
        recursion_iframes(browser, iframe_paths, iframe_path)


# 切换到目标iframe
def switch_target_iframe(browser, iframe_path=''):
    browser.switch_to.default_content()
    arr = iframe_path.split('/')
    for i in range(1, len(arr)):
        id_name_index = arr[i][1:len(arr[i])-1].split(":")
        iframe = browser.find_elements_by_css_selector("iframe")[int(id_name_index[2])]
        browser.switch_to.frame(iframe)
        # if id_and_name[0] != '':
        #     browser.switch_to.frame(id_and_name[0])
        # elif id_and_name[1] != '':
        #     browser.switch_to.frame(id_and_name[1])


if __name__ == '__main__':
    # chrome_options = Options()
    # chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")
    # chrome_driver = r'C:\Users\wj\AppData\Local\Google\Chrome\Application\chrome.exe'
    # chromeBrowser = webdriver.Chrome(chrome_driver, chrome_options=chrome_options)

    chromePath = r'C:\Users\wj\AppData\Local\Google\Chrome\Application\chrome.exe'
    webbrowser.register('chrome', None, webbrowser.BackgroundBrowser(chromePath))
    chromeBrowser = webdriver.Chrome()

    chromeBrowser.get('http://localhost:63343/untitled/iframe.html')
    chromeBrowser.maximize_window()
    chromeBrowser.set_window_size(2560, 1600)
    i_paths = query_all_iframe(chromeBrowser)
    print(i_paths)
    switch_target_iframe(chromeBrowser, i_paths[2])
    elem = chromeBrowser.find_elements_by_css_selector("#btn2")[0]
    elem.click()
    # chromeBrowser.switch_to.default_content()
    # chromeBrowser.switch_to.frame('iframe2')

